var info = {};
var headers = {
    "lepan.cc":{
        host: "www.lepan.cc"
    }
};
var resourceDomains = [];
var expFlg = false;
var covertDomains = {
    "2bbd.com":"2kuai.com",
    "2rbb.com":"lepan.cc",
    "suwpan.com":"sufile.com"
}
function parseCookie(cookieStr){
    var cookie = {};
    var cookieArry = cookieStr.split(";");
    for(var i = 0; i < cookieArry.length; i++){
        var c = cookieArry[i].split("=");
        if(c.length == 2)
            cookie[c[0]] = c[1];
    }
    return cookie;
}
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.domain){
        if(request.cookie){
            request.cookie = parseCookie(request.cookie.replace(/\s/g,""));
        }
        info[request.domain] = request;
    }
    if(request.topic == "download"){
        chrome.downloads.download(request.options);
    }
    if(request.topic == "resource"){
        if(request.cmd == "addDomain"){
            covertDomains[request.domain] && (request.domain = covertDomains[request.domain]);
            addArray(request.domain, resourceDomains);
            // for(var i = 0; i < resourceDomains.length; i++){
            //     if(resourceDomains[i] == request.domain){
            //         break
            //     }
            // }
            // if(i == resourceDomains.length){
            //     resourceDomains.push(request.domain);
            // }
            sendResponse({"visitedFlg":1});
        }else if(request.cmd == "addExpDomain"){
            expFlg = true;
            chrome.tabs.getCurrent(function(tab){
                console.log(tab)
            })
        }
    }else if (request.topic == "css"){
        chrome.tabs.insertCSS(sender.tab.id, {file:request.file}, function(){}) 
    }
}); 
chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        // var lepan = info["lepan.cc"];
        var header = {};
        if(details.url.match(/www\.lepan\.cc\/file/) && !headers["lepan.cc"].cookie){
            for (var i = 0; i < details.requestHeaders.length; ++i) {
                header = details.requestHeaders[i];
                if(header.name === 'Cookie'){
                    headers["lepan.cc"].cookie = header.value;
                    break;
                }
            }
        }
        if (details.url.match(/www\.lepan\.cc\/down/)|| details.url.match(/f\d*\.lepan\.cc\/dl\.php/)) {
            var refFlg = false;
            var cookieFlg = false;
            var hostFlg = false;
            var ref = details.url.replace("down-","file-");
            for (var i = 0; i < details.requestHeaders.length; ++i) {
                header = details.requestHeaders[i];
                if (header.name === 'Referer') {
                    refFlg = true;
                    header.value = ref;
                }
                if(header.name === 'Cookie'){
                    cookieFlg = true;
                    // header.value = headers["lepan.cc"].cookie;
                }
                if(header.name === 'Host'){
                    hostFlg = true;
                    // header.value = headers["lepan.cc"].host;
                }
            }

            if (!refFlg) {
                details.requestHeaders.push({ name: 'Referer', value: ref});
            }
            if (!cookieFlg) {
                details.requestHeaders.push({ name: 'Cookie', value: headers["lepan.cc"].cookie});
            }
            if (!hostFlg) {
                details.requestHeaders.push({ name: 'Host', value: headers["lepan.cc"].host});
            }

             return { requestHeaders: details.requestHeaders };
         }
        //  if (details.url.match(/f\d\.lepan\.cc/) && lepan.file_id && lepan.cookie.server_id && lepan.cookie.PHPSESSID) {
        //     var exists = false;
        //     var cookieExistes = false;
        //     var cookie = 'PHPSESSID='+lepan.cookie.PHPSESSID+'; server_id='+lepan.cookie.server_id+'; bdshare_firstime=1400859554235; view_stat=1; hqCheck_3541431801=1; hqCheck_3541431990=1; hqCheck_3541430753=1; BAIDU_DUP_lcr=http://www.viidii.info/?http://www______lepan______cc/file-'+lepan.file_id+'______html&z; fmtopenTime=0; smartad_cookie_cpv_close=0; smartad_cookie_cpv_count=1; shanda888=popupshanda888; CNZZDATA83875507=cnzz_eid%3D1450534930-1400859546-%26ntime%3D1401504352%26cnzz_a%3D22%26sin%3Dhttp%253A%252F%252Fwww.lepan.cc%252Ffile-'+lepan.file_id+'.html%26ltime%3D1401498681527%26rtime%3D3; AJSTAT_ok_pages=23; AJSTAT_ok_times=5; CNZZDATA5827173=cnzz_eid%3D1577224672-1400859550-%26ntime%3D1401504444%26cnzz_a%3D22%26sin%3Dhttp%253A%252F%252Fwww.lepan.cc%252Ffile-'+lepan.file_id+'.html%26ltime%3D1401498681974%26rtime%3D3';
        //     var header = {};
        //     for (var i = 0; i < details.requestHeaders.length; ++i) {
        //         header = details.requestHeaders[i];
        //         if (header.name === 'Referer' && !header.value.match(/http:\/\/www\.lepan\.cc\/file-\d*\.html/)) {
        //             exists = true;
        //             details.requestHeaders[i].value = 'http://www.lepan.cc/file-'+lepan.file_id+'.html';
        //             break;
        //         }
        //         if(details.requestHeaders[i].name === 'Cookie' && !header.value.match(/PHPSESSID=/)){
        //             cookieExistes = true;
        //             details.requestHeaders[i].value = cookie;
        //             break;
        //         }
        //     }

        //     if (!exists) {
        //         details.requestHeaders.push({ name: 'Referer', value: 'http://www.lepan.cc/file-'+lepan.file_id+'.html'});
        //     }
        //     if (!cookieExistes) {
        //         details.requestHeaders.push({ name: 'Cookie', value: cookie});
        //     }

        //      return { requestHeaders: details.requestHeaders };
        //  }
         // if(details.url.match(/www\.rmdown\.com\/download\.php/)){
         //    var refExists = false;
         //    var conExists = false;
         //    var header = {};
         //    var hash = "";
         //    for (var i = 0; i < details.requestHeaders.length; i++) {
         //        header = details.requestHeaders[i];
         //        // if(header.name === "hash"){
         //        //     hash = header.value;
         //        //     header = null;
         //        // }
         //        if (header.name === 'Host' && !header.value.match(/http:\/\/www\.rmdown\.com/)) {
         //            refExists = true;
         //            header.value = 'http://www.rmdown.com';
         //        }
         //        if (header.name === 'Origin' && !header.value.match(/http:\/\/www\.rmdown\.com/)) {
         //            refExists = true;
         //            header.value = 'http://www.rmdown.com';
         //        }
         //        if (header.name === 'Referer' && !header.value.match(/http:\/\/www\.rmdown\.com\/link\.php/)) {
         //            refExists = true;
         //            header.value = 'http://www.rmdown.com/link.php?hash=';
         //        }
         //        if (header.name === 'Connection') {
         //            conExists = true;
         //            header.value = 'keep-alive';
         //        }
         //    }
         //    // if (!refExists) {
         //    //     details.requestHeaders.push({ name: 'Referer', value: 'http://www.rmdown.com/link.php?hash='+hash});
         //    // }
         //    if (!conExists) {
         //        details.requestHeaders.push({ name: 'Connection', value: 'keep-alive'});
         //    }

         //     return { requestHeaders: details.requestHeaders };
         // }
    },
    // 'http://f1.lepan.cc/*',
    //         'http://f2.lepan.cc/*',
    //         'http://f3.lepan.cc/*',
    //         'http://f4.lepan.cc/*',
    //         'http://f5.lepan.cc/*',
    //         'http://cl.man.lv/*',
    //         'http://www.rmdown.com/*'
    {urls: ["<all_urls>"]},
    ["blocking", "requestHeaders"]
);
var urls = [
'http://www.lepan.cc/*',
'http://t.tukj.net/code/*',
'http://f.tukj.net/code/*',
'http://pq.o091i.com/*',
'http://cpro.baidustatic.com/*',
'http://js.6dad.com/js/*',
'http://code.ze5.com/*',
'http://a.okokw.com/*',
'http://4.qqm98.com/js/*',
'http://good.baigm.com/js/*'
]
var domains = {};
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
    if(details.url.match(/^[^?]*\.(flv|mp4)/i)){
        chrome.tabs.sendMessage(details.tabId, {
            topic:"download",
            cmd:"add-icon",
            url:details.url
        }, function (){}) 
    }
},
{urls: ["<all_urls>"]},
["blocking"]);
chrome.webRequest.onBeforeRequest.addListener(
function(details) {

    var url = "";
    var domain ="";
    var i = 0;
    if(details.tabId && !domains[details.tabId] && details.tabId >=0){
        chrome.tabs.get(details.tabId, function(tab){
            url = tab.url;
            domains[details.tabId] = util.getDomain(url);
            covertDomains[domains[details.tabId]] && (domains[details.tabId] = covertDomains[domains[details.tabId]]);
        });
        domains[details.tabId] = "1";
    }
    domain = domains[details.tabId];
    !domain && (domain = "#");
    var rule = rules[domain];
    var domainFlg = false;
    for(var i = 0; i < resourceDomains.length; i++){
        if(domain == resourceDomains[i]){
            domainFlg = true;
            break;
        }
    }
    return {cancel: domains[details.tabId] != "1" && domainFlg && (!!details.url.match(/((cp|atpopjs7|c)\.js)|((popjs|pop_cpf)\.asp)|(getcode.jsp)|(ps.aspx)|(360\.safe\.go\.360safego\.com\/js)/) || details.url.indexOf(domain) < 0)};
},
{urls: ["<all_urls>"]},
["blocking"]);
// chrome.webRequest.onBeforeRedirect.addListener(
// function(details) {
//     var domain = util.getDomain(details.redirectUrl);
//     domains[details.tabId] && (domains[details.tabId] = domain);
//     resourceDomains.push(domain);
// },
// {urls: ["<all_urls>"]},
// ["responseHeaders"]) 
// var counter = {};
// chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){

//     if(changeInfo.url){
//         if(counter[tabId] == 1){
//             var domain = util.getDomain(changeInfo.url);
//             domains[tabId] && (domains[tabId] = domain);
//             addArray(domain, resourceDomains);
//             delete counter[tabId];
//         }
//         counter[tabId] = 1;
//     }
// }) 

function addArray(item, array){
    for(var i = 0; i < array.length; i++){
        if(array[i] == item){
            break
        }
    }
    if(i == array.length){
        array.push(item);
    }
}